package main

import (
	"fmt"
	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
	_ "gopkg.in/mgo.v2/bson"
	"log"
)


type Student struct {
	Id bson.ObjectId `bson:"_id"`
	Name string `bson:"name"`
	Phone string `bson:phone`
	Email string `bson:email`
	Sex string `bson:sex`

}

func ConnectToDB() *mgo.Collection{
	session, err := mgo.Dial("118.25.149.63:27017")
	if err != nil {
		panic(err)
	}

	//为session设置一致性模式
	/*
	Strong  一致性模式（默认）
	Monotonic 一致性模式
	Eventual 一致性模式
	*/
	session.SetMode(mgo.Monotonic, true)
	c := session.DB("gene").C("student")
	return c
}

func Insert() {
	conn := ConnectToDB()
	id := bson.NewObjectId()
	stu1:= Student{
		Id:id,
		Name:"gene",
		Phone:"13211109878",
		Email:"ss@163.com",
		Sex:"F",
	}
	err := conn.Insert(stu1)
	if err != nil {
		log.Fatal(err)
	}
}

//返回一条数据
func GetOneData(){
	c := ConnectToDB()
	student := Student{}
	err := c.Find(bson.M{"sex": "M"}).One(&student)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("student", student)
}

//集合
func List(){
	conn := ConnectToDB()
	students := make([]Student, 20)
	err := conn.Find(nil).All(&students)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(students)
}

//根据ID查询
func GetDataById(id string) Student{
	idObj := bson.ObjectIdHex(id)
	c := ConnectToDB()
	student := Student{}
	err := c.FindId(idObj).One(&student)
	if err!=nil {
		log.Fatal(err)
	}
	return student
}

//更新 只更新符合条件的一条数据
func UpdateByCondition(){
	c := ConnectToDB()
	err := c.Update(bson.M{"email": "ss@163.com"}, bson.M{"$set": bson.M{"name": "hone", "phone": "13512340000"}})
	if err!=nil {
		log.Fatal(err)
	}
}


func UpdateAll(){
	c := ConnectToDB()
	info, err := c.UpdateAll(bson.M{"email": "ss@163.com"}, bson.M{"$set": bson.M{"phone": "18500001111"}})
	if err!=nil {
		log.Fatal(err)
	}
	fmt.Println(info)
}

func UpdateById(id string){
	c := ConnectToDB()
	objectId := bson.ObjectIdHex(id)
	info, err := c.UpdateAll(bson.M{"_id": objectId}, bson.M{"$set": bson.M{"name": "genezhao"}})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(info)
}


func DeleteByCondition(){
	c := ConnectToDB()
	err := c.Remove(bson.M{"sex": "F"})
	if err != nil {
		log.Fatal(err)
	}

}

func main() {
	//Insert()
	//GetOneData()
	//List()
	//student := GetDataById("5c1e0b95cffe6ee224bfdba1")
	//fmt.Println(student)
	//UpdateByCondition()
	//UpdateAll()
	//UpdateById("5c1e0b95cffe6ee224bfdba1")
	DeleteByCondition()
}